﻿//-----------------------------------------------------------------------
// <copyright file="Decoder.cs" company="iTunesEncodeNet">
//  (c) 2009 Vlasenko Dmitry
// </copyright>
//-----------------------------------------------------------------------

namespace ITunesEncodeNet
{
    using System;
    using System.Diagnostics;
    using System.IO;

    /// <summary>
    /// Provides methods for decoding *.flac and *.ape files into *.wav files.
    /// </summary>
    internal class Decoder
    {
        /// <summary>
        /// Encoder type.
        /// </summary>
        private EncoderOptions.EncoderType type;

        /// <summary>
        /// Initializes a new instance of the Decoder class.
        /// </summary>
        /// <param name="type">Encoder type.</param>
        public Decoder(EncoderOptions.EncoderType type)
        {
            this.type = type;
        }

        /// <summary>
        /// Decodes *.flac or *.ape file into *.wav file.
        /// </summary>
        /// <param name="fileName">Full path to initial file.</param>
        /// <param name="destinationDirName">Full path to destination directory.</param>
        /// <returns>Name of result *.wav file.</returns>
        public string Decode(string fileName, string destinationDirName)
        {
            string tempName = Guid.NewGuid().ToString() + ".wav";
            string resultName = Path.Combine(destinationDirName, tempName);

            Process process = new Process();
            ProcessStartInfo startInfo = new ProcessStartInfo();

            switch (this.type)
            {
                case EncoderOptions.EncoderType.flac:
                    startInfo = new ProcessStartInfo(EncoderOptions.FlacPath, string.Format("-d --totally-silent --output-name=\"{0}\" \"{1}\"", resultName, fileName));
                    break;

                case EncoderOptions.EncoderType.ape:
                    startInfo = new ProcessStartInfo(EncoderOptions.ApePath, string.Format("\"{0}\" \"{1}\" -d", fileName, resultName));
                    break;
            }

            startInfo.UseShellExecute = false;
            startInfo.CreateNoWindow = true;

            process = Process.Start(startInfo);
            process.WaitForExit();

            if (process.ExitCode != 0)
            {
                return null;
            }

            return resultName;
        }
    }
}
